package io.kimmking.rpcfx.netty;

import com.alibaba.fastjson.JSON;
import io.kimmking.rpcfx.api.RpcfxRequest;
import io.kimmking.rpcfx.api.RpcfxResponse;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;


public class ClientHandler extends ChannelInboundHandlerAdapter  {
    private String url;
    private String body;
    private String host;
    private RpcfxResponse rpcfxResponse;
    private int port;
    public  ClientHandler(String url, String body, RpcfxResponse rpcfxResponse) throws MalformedURLException {
        URL uri = new URL(url);
        this.host = uri.getHost();
        this.port = uri.getPort() == -1 ? 80 : uri.getPort();
        this.url = url;
        this.body = body;
        this.rpcfxResponse = rpcfxResponse;
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        FullHttpResponse response = (FullHttpResponse) msg;

        ByteBuf content = response.content();
        HttpHeaders headers = response.headers();
        RpcfxResponse res = JSON.parseObject(content.toString(CharsetUtil.UTF_8), RpcfxResponse.class);
        rpcfxResponse.setResult(res.getResult());
        rpcfxResponse.setException(res.getException());
        rpcfxResponse.setStatus(res.isStatus());
        ctx.channel().close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        URI uri = new URI(url);
        //配置HttpRequest的请求数据和一些配置信息
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.toASCIIString(), Unpooled.wrappedBuffer(body.getBytes("UTF-8")));

        request.headers()
                .set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8")
                //开启长连接
                .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE)
                //设置传递请求内容的长度
                .set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes())
                .set(HttpHeaderNames.HOST,host+":"+port);
        //发送数据
        ctx.writeAndFlush(request);
    }
}
